package com.qianchang.microfinance.view.credit.data;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.HttpParams;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.BitmapUtils;
import com.dm.library.utils.DMLog;
import com.dm.library.utils.FormatUtil;
import com.dm.library.utils.StringUtils;
import com.dm.library.utils.ToastUtil;
import com.dm.library.utils.ViewUtils;
import com.dm.library.widgets.OneLineEditLinearLayout;
import com.dm.library.widgets.element.DButton;
import com.dm.library.widgets.element.DTextView;
import com.qianchang.microfinance.bean.IdCardBackBean;
import com.qianchang.microfinance.bean.IdCardFrontBean;
import com.qianchang.microfinance.bean.IdentityInfoBean;
import com.qianchang.microfinance.bean.IdentityVeriBean;
import com.qianchang.microfinance.bean.IdentityVerificationInfoBean;
import com.qianchang.microfinance.bean.event.AgreementTitleBean;
import com.qianchang.microfinance.utils.SpanUtils;
import com.qianchang.microfinance.utils.UUIDS;
import com.qianchang.microfinance.view.MainActivity;
import com.qianchang.microfinance.view.register.AgreementActivity;
import com.qianchang.microfinance.view.register.AgreementApi;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.FindUserBasicInfoBean;
import com.qianchang.microfinance.bean.IdentifyIdCardBean;
import com.qianchang.microfinance.bean.UploadFileBean;
import com.qianchang.microfinance.global.ConstantAppInfo;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.view.base.ImageChoseActivity;
import com.qianchang.microfinance.widgets.glidetransform.GlideRoundTransform;
import com.megvii.idcardlib.IDCardScanActivity;
import com.megvii.idcardquality.IDCardQualityLicenseManager;
import com.megvii.idcardquality.bean.IDCardAttr;
import com.megvii.licensemanager.Manager;

import org.json.JSONArray;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.os.Build.VERSION_CODES.M;
import static com.qianchang.microfinance.utils.HSBitmapUtils.createFile;

/**
 * 版 权: 深圳市迪蒙网络科技有限公司
 * 描 述:实名认证
 * 修 改 人: zhoulai
 * 修改时间: 2017/8/12 9:21
 */


public class ScanIdentityActivity extends ImageChoseActivity implements OneLineEditLinearLayout.TextWatcher, ImageChoseActivity.UpLoadFileCallback {


    private static final String TAG = "ScanIdentityActivity";
    @BindView(R.id.tll_real_name)
    OneLineEditLinearLayout tllRealName;
    @BindView(R.id.tll_identity_number)
    OneLineEditLinearLayout tllIdentityNumber;
    @BindView(R.id.iv_positive_img)
    ImageView ivPositiveImg;
    @BindView(R.id.iv_negative_img)
    ImageView ivNegativeImg;
    @BindView(R.id.btn_identify_photo_commit)
    DButton btnIdentifyPhotoCommit;
    @BindView(R.id.ll_content)
    LinearLayout llContent;
    @BindView(R.id.tv_tips)
    DTextView tvTips;
    @BindView(R.id.iv_negative_add)
    ImageView ivNegativeAdd;
    @BindView(R.id.iv_positive_add)
    ImageView ivPositiveAdd;
    @BindView(R.id.tv_protocol)
    DTextView tvProtocol;


    private String realName;
    private String idCard;
    private String idCardFrontUrl;
    private String idCardBackUrl;

    private static final int FRONT_ADD = 0;
    private static final int BACK_ADD = 1;
    private FindUserBasicInfoBean basicInfoBean;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_identity);
        ButterKnife.bind(this);
        initView();
        initData();
        network();

        isCertified();          //判断用户是否提交过身份证验证

        AgreementData();

    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    private boolean isConfirml = false;

    @Override
    protected void initView() {
        super.initView();
        String title = getString(R.string.label_info_identity);
        setTitle(title);
        //设置实名和身份证长度
        tllRealName.setMaxLength(10);
        tllIdentityNumber.setMaxLength(18);
        setMaxImageCount(1);
        setUpLoadCallBackListener(this);
        Bundle bundle = getBundle();
        if (null != bundle) {
            basicInfoBean = (FindUserBasicInfoBean) bundle.getSerializable(ConstantAppInfo.BASIC_INFO_BEAN);
            isConfirml = bundle.getBoolean("isConfirml",false);
            if (null != basicInfoBean) {
                //如果基本信息不为空 则刷新
                refreshView();
            }
            if (basicInfoBean == null) {
                basicInfoBean = new FindUserBasicInfoBean();
            }
        }
    }

    //
    private void refreshView() {
        switch (basicInfoBean.getIsIdCardCheckThrough()) {//实名认证是否通过，0：是、1：否
            case 0://已经通过 只能预览
                ViewUtils.disableSubControls(tllRealName);
                tvTips.setVisibility(View.GONE);
                initHasSubmitView();
                break;
            case 1: //可以点击添加正反面
                tllRealName.setTextWatcher(this, 0);
                tllIdentityNumber.setTextWatcher(this, 1);
                ivNegativeAdd.setVisibility(View.VISIBLE);
                ivPositiveAdd.setVisibility(View.VISIBLE);
                tllRealName.setEnabled(true);
                tllIdentityNumber.setEnabled(true);
                btnIdentifyPhotoCommit.setVisibility(View.VISIBLE);
                btnIdentifyPhotoCommit.setEnabled(true);
                tvTips.setVisibility(View.VISIBLE);

                break;
            default:
                //显示提交按钮
                initHasSubmitView();
                break;
        }
        ViewUtils.disableSubControls(tllIdentityNumber);
    }

    private void initHasSubmitView() {
        ivNegativeAdd.setVisibility(View.GONE);
        ivPositiveAdd.setVisibility(View.GONE);
        String realName = basicInfoBean.getRealName();
        String idCard = basicInfoBean.getIdCard();

        if (!TextUtils.isEmpty(realName) && realName.length() > 1) {
            tllRealName.setRightContent("*" + realName.substring(1));
        }
        if (!TextUtils.isEmpty(idCard) && idCard.length() > 4) {
            tllIdentityNumber.setRightContent(idCard.substring(0, 2) + " *** *** *** " + idCard.substring(idCard.length() - 2));
        }
        btnIdentifyPhotoCommit.setVisibility(View.INVISIBLE);
        Glide.with(this).load(DMConstant.Config.BASE_URL + basicInfoBean.getIdCardFrontUrl()).error(R.drawable.img_jzsb).into(ivPositiveImg);
        Glide.with(this).load(DMConstant.Config.BASE_URL + basicInfoBean.getIdCardBackUrl()).error(R.drawable.img_jzsb).into(ivNegativeImg);
        DMLog.d(DMConstant.Config.BASE_URL + basicInfoBean.getIdCardFrontUrl());
        DMLog.d(DMConstant.Config.BASE_URL + basicInfoBean.getIdCardBackUrl());
    }

    @Override
    protected void initData() {
        super.initData();
    }


    @OnClick({R.id.iv_negative_add, R.id.iv_positive_add, R.id.btn_identify_photo_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_negative_add:      //身份证反面
                setFlag(BACK_ADD);
//                openCamora();             //2018.1.11注释掉迪蒙代码

                if(isAuthState){                //授权成功
                    requestCameraPerm(1);
                }else{
                    network();                   //授权失败重新授权
                }

                break;
            case R.id.iv_positive_add:          //身份证正面
                setFlag(FRONT_ADD);
//                openCamora();                   //2018.1.11注释掉迪蒙代码

                if(isAuthState){                    //授权成功
                    requestCameraPerm(0);
                }else{                              //授权失败重新授权
                    network();
                }

                break;
            case R.id.btn_identify_photo_commit:
//                submit();   //2018.1.11注释掉迪蒙代码

                hsSubmit();     //鸿胜科技新增2018.1.17
                break;
        }
    }

    private void openCamora() {
        initImagePickerForTakePhoto();
        Intent intent = new Intent(this, ImageGridActivity.class);
        intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
        startActivityForResult(intent, REQUEST_CODE_SELECT);
    }

    private void submit() {
//        1	userId	Y	用户ID
//        2	idCard	Y	身份证号
//        3	type	Y	类型 传0
//        4	idCardFrontUrl	Y	身份证正面url
//        5	idCardBackUrl	Y	身份证反面url
        HttpParams params = new HttpParams();

        if (StringUtils.isEmptyOrNull(idCardFrontUrl)) {
            ToastUtil.getInstant().show(ScanIdentityActivity.this, getString(R.string.msg_idCard_front_image_is_null));
            return;
        }
        if (StringUtils.isEmptyOrNull(idCardBackUrl)) {
            ToastUtil.getInstant().show(ScanIdentityActivity.this, getString(R.string.msg_idCard_back_image_is_null));
            return;
        }

        if (!FormatUtil.isValidName(realName)) {
            ToastUtil.getInstant().show(ScanIdentityActivity.this, getString(R.string.msg_name_not_null));
            return;
        }

        if (!FormatUtil.isValidIdCard(idCard)) {
            ToastUtil.getInstant().show(ScanIdentityActivity.this, getString(R.string.msg_idCard_not_ok));
            return;
        }


        show();
        params.put("idCard", idCard);//basicInfoBean.getIdCard());
        params.put("realName", realName);
        params.put("type", "0");
        params.put("idCardFrontUrl", idCardFrontUrl);
        params.put("idCardBackUrl", idCardBackUrl);
        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.SUBMIT_RealName_Auth, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(JsonResult<String> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    ScanIdentityActivity.this.finish();
                } else {
                    ToastUtil.getInstant().show(ScanIdentityActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(ScanIdentityActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }

    //useless
    @Override
    public void afterTextChanged(Editable s, int flag) {
        switch (flag) {
            case 0:
                realName = s.toString().trim();
                break;
            case 1:
                idCard = s.toString().trim();
                break;
        }
    }


    @Override
    public void onPhotoResult(ArrayList<ImageItem> imageItems, int flag) {
        if (null != imageItems && imageItems.size() > 0) {
            ImageItem imageItem = imageItems.get(0);
            String filePath = imageItem.getPath();
            String file = BitmapUtils.createFile(this, filePath);
            uploadFile(file);
            clearSelectImages();
        }
    }

    @Override
    public void onUpLoadSuccess(UploadFileBean uploadFileBean, final String imagePath, int flag) {
        HttpParams params = new HttpParams();
        switch (flag) {
            case FRONT_ADD:
                idCardFrontUrl = uploadFileBean.getUrl();
                show();
                params.put("url", idCardFrontUrl);
                DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.EXECUTE_OCR_INTERFACE, params, new RequestCallBack<IdentifyIdCardBean>() {
                    @Override
                    public void onSuccess(JsonResult<IdentifyIdCardBean> response) {
                        dismiss();
                        if (response.isReqDataSuccess()) {
                            IdentifyIdCardBean identifyIdCardBean = response.getObject();
                            if (null != identifyIdCardBean) {
                                idCard = identifyIdCardBean.getIdCard();
                                realName = identifyIdCardBean.getRealName();
                                tllRealName.setRightContent(realName);
                                tllIdentityNumber.setRightContent(idCard);
                                Glide.with(ScanIdentityActivity.this).load(imagePath).transform(new GlideRoundTransform(ScanIdentityActivity.this, 10)).error(R.drawable.img_sfzzm).into(ivPositiveImg);
                            }
                        } else {
                            idCardFrontUrl = null;
                            ToastUtil.getInstant().show(ScanIdentityActivity.this, response.getDescription());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        dismiss();
                        idCardFrontUrl = null;
                        ToastUtil.getInstant().show(ScanIdentityActivity.this, msg);

                    }

                    @Override
                    public void onConnectFailure(String msg) {

                    }
                });
                break;
            case BACK_ADD:
                idCardBackUrl = uploadFileBean.getUrl();
                show();
                params.put("url", idCardBackUrl);
                DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.EXECUTE_OCR_FRONTINTER_FACE, params, new RequestCallBack<Object>() {
                    @Override
                    public void onSuccess(JsonResult<Object> response) {
                        dismiss();
                        if (response.isReqDataSuccess()) {
                            Glide.with(ScanIdentityActivity.this).load(imagePath).transform(new GlideRoundTransform(ScanIdentityActivity.this, 10)).error(R.drawable.img_sfzfm).into(ivNegativeImg);
                        } else {
                            idCardFrontUrl = null;
                            ToastUtil.getInstant().show(ScanIdentityActivity.this, response.getDescription());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        dismiss();
                        idCardBackUrl = null;
                        ToastUtil.getInstant().show(ScanIdentityActivity.this, msg);

                    }

                    @Override
                    public void onConnectFailure(String msg) {

                    }
                });

                break;
        }
    }

    //身份证扫描首先要联网授权
    private void network() {
        show("联网授权中....");
        new Thread(new Runnable() {
            @Override
            public void run() {
                Manager manager = new Manager(ScanIdentityActivity.this);
                IDCardQualityLicenseManager idCardLicenseManager = new IDCardQualityLicenseManager(ScanIdentityActivity.this);
                manager.registerLicenseManager(idCardLicenseManager);
                String deviceId = UUIDS.buidleID(ScanIdentityActivity.this.getApplicationContext()).getUUIDS();
                String uuid = deviceId;
                manager.takeLicenseFromNetwork(uuid);
                String contextStr = manager.getContext(uuid);
                Log.w("ceshi", "contextStr====" + contextStr);

                Log.w("ceshi", "idCardLicenseManager.checkCachedLicense()===" + idCardLicenseManager.checkCachedLicense());
                if (idCardLicenseManager.checkCachedLicense() > 0)  //授权大于0 则可用
                    UIAuthState(true);
                else
                    UIAuthState(false);
            }
        }).start();
    }

    private void UIAuthState(final boolean isSuccess) {
        runOnUiThread(new Runnable() {
            public void run() {
                authState(isSuccess);
            }
        });
    }

    private boolean isAuthState = false;    //相机权限授权
    private void authState(boolean isSuccess) {
        dismiss();
        if (isSuccess) {
            isAuthState = true;
        } else {
            isAuthState = false;
            ToastUtil.getInstant().show(ScanIdentityActivity.this,"联网授权失败！请检查网络或找服务商");
        }
    }


    int mSide = 0;
    private static final int INTO_IDCARDSCAN_PAGE = 100;
    private boolean isVertical = true;

    private void requestCameraPerm(int side) {
        mSide = side;
        enterNextPage(side);
    }

    //跳转至拍照界面
    private void enterNextPage(int side){
        Intent intent = new Intent(this, IDCardScanActivity.class);
        intent.putExtra("side", side);
        intent.putExtra("isvertical", isVertical);
        startActivityForResult(intent, INTO_IDCARDSCAN_PAGE);
    }


    IDCardAttr.IDCardSide mIDCardSide;
    private String positivePath = "";       //身份证图片正面路径
    private String OppositePath = "";       //身份证图片反面路径

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == INTO_IDCARDSCAN_PAGE && resultCode == RESULT_OK) {
            int mside = data.getIntExtra("side", 0);
            mIDCardSide = mside == 0 ? IDCardAttr.IDCardSide.IDCARD_SIDE_FRONT : IDCardAttr.IDCardSide.IDCARD_SIDE_BACK;

            if (mIDCardSide == IDCardAttr.IDCardSide.IDCARD_SIDE_FRONT){        //身份证正面
                byte[] img = data.getByteArrayExtra("idcardImg");
                positivePath = createFile(img);
                data.getByteArrayExtra("portraitImg");
//                Glide.with(ScanIdentityActivity.this).load(img).transform(new GlideRoundTransform(ScanIdentityActivity.this, 10)).error(R.drawable.img_sfzzm).into(ivPositiveImg);
                hsUploadFile(positivePath);

            }else {        //身份证反面
                byte[] bimg = data.getByteArrayExtra("idcardImg");
                data.getByteArrayExtra("portraitImg");
//                Glide.with(ScanIdentityActivity.this).load(bimg).transform(new GlideRoundTransform(ScanIdentityActivity.this, 10)).error(R.drawable.img_sfzzm).into(ivNegativeImg);

                OppositePath = createFile(bimg);
                hsUploadBackFile(OppositePath);
            }
        }
    }


    private void cleaPositivePath(){
        positivePath = null;
    }

    private void cleaOppositePath(){
        OppositePath = null;
    }

    //上传身份证正面
    private void hsUploadFile(String imagePath){
        if (null == imagePath) {
            return;
        }

        File file = new File(imagePath);
        Map<String, File> files = new HashMap<>();
        files.put(file.getName(), file);
        Map<String, String> fileParamsMap = new HashMap<>();
        fileParamsMap.put("frontImg", "jpg,png");
        fileParamsMap.put("fileType", "0");
        fileParamsMap.put("isTransform", "false");
        show();

        DMOKHttpUtils.getInstance().uploadFile(this, DMConstant.ApiURL.EXCUTE_FACE_PLUSORCIDENTITY_FRONT, fileParamsMap, "uploadFile", files, new RequestCallBack<IdCardFrontBean>() {

            @Override
            public void onSuccess(JsonResult<IdCardFrontBean> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    IdCardFrontBean idCardFrontBean = response.getObject();
                    if (idCardFrontBean != null && idCardFrontBean.getStatus().equals("1")) {
                        IdentityInfoBean identityInfoBean = idCardFrontBean.getIdentityInfo();
                        String forontImg = idCardFrontBean.getFrontImg();
                        if (identityInfoBean != null) {
                            idCard = identityInfoBean.getIDCard();  //身份证号
                            realName = identityInfoBean.getName();  //姓名
                            tllRealName.setRightContent(realName);  //姓名UI
                            tllIdentityNumber.setRightContent(idCard);  //身份证号UI
                            Glide.with(ScanIdentityActivity.this).load(forontImg).transform(new GlideRoundTransform(ScanIdentityActivity.this, 10)).error(R.drawable.img_sfzzm).into(ivPositiveImg);
                        }
                    }
                } else {
                    ToastUtil.getInstant().show(ScanIdentityActivity.this, response.getDescription());
                }
                isCertified();  //上传完重新刷新
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(ScanIdentityActivity.this, msg);
                isCertified();  //上传完重新刷新
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }

    //上传身份证背面
    private void hsUploadBackFile(String imagePath){
        if (null == imagePath) {
            return;
        }

        File file = new File(imagePath);
        Map<String, File> files = new HashMap<>();
        files.put(file.getName(), file);
        Map<String, String> fileParamsMap = new HashMap<>();
        fileParamsMap.put("frontImg", "jpg,png");
        fileParamsMap.put("fileType", "0");
        fileParamsMap.put("isTransform", "false");
        show();

        DMOKHttpUtils.getInstance().uploadFile(this, DMConstant.ApiURL.EXCUTE_FACE_PLUS_ORCIDENTITY_REVERSE, fileParamsMap, "uploadFile", files, new RequestCallBack<IdCardBackBean>() {

            @Override
            public void onSuccess(JsonResult<IdCardBackBean> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    IdCardBackBean idCardBackBean = response.getObject();
                    if(idCardBackBean != null){
                        String backImgPath = idCardBackBean.getReverseImg();
                        Glide.with(ScanIdentityActivity.this).load(backImgPath).transform(new GlideRoundTransform(ScanIdentityActivity.this, 10)).error(R.drawable.img_sfzfm).into(ivNegativeImg);
                    }
                } else {
                    ToastUtil.getInstant().show(ScanIdentityActivity.this, response.getDescription());
                }

                isCertified();  //上传完重新刷新
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(ScanIdentityActivity.this, msg);
                isCertified();  //上传完重新刷新
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }

    private void hsSubmit(){

        if (StringUtils.isEmptyOrNull(positivePath)) {
            ToastUtil.getInstant().show(ScanIdentityActivity.this, getString(R.string.msg_idCard_front_image_is_null));
            return;
        }
        if (StringUtils.isEmptyOrNull(OppositePath)) {
            ToastUtil.getInstant().show(ScanIdentityActivity.this, getString(R.string.msg_idCard_back_image_is_null));
            return;
        }

        if (!FormatUtil.isValidName(realName)) {
            ToastUtil.getInstant().show(ScanIdentityActivity.this, getString(R.string.msg_name_not_null));
            return;
        }

        if (!FormatUtil.isValidIdCard(idCard)) {
            ToastUtil.getInstant().show(ScanIdentityActivity.this, getString(R.string.msg_idCard_not_ok));
            return;
        }


        show();
        HttpParams params = new HttpParams();
        params.put("name", realName);
        params.put("IDCard", idCard);
        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.EXECUTEIDENTITY_VERIFICATION, params, new RequestCallBack<IdentityVeriBean>() {

            @Override
            public void onSuccess(JsonResult<IdentityVeriBean> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
//                    ScanIdentityActivity.this.finish();               //注释迪蒙原来代码
                    IdentityVeriBean identityVeriBean = response.getObject();
                    if(identityVeriBean != null){
                        String status = identityVeriBean.getStatus();
                        if("1".equals(status)){
                            updateStatus(); //鸿盛科技新增代码2018.1.17
                        }else if("-1".equals(status)) {
                            String msg = identityVeriBean.getMessage();
                            ToastUtil.getInstant().show(ScanIdentityActivity.this,msg);
                        }else {
                            ToastUtil.getInstant().show(ScanIdentityActivity.this,"数据异常");
                        }
                    }else {
                        ToastUtil.getInstant().show(ScanIdentityActivity.this, response.getDescription());
                    }
                } else {
                    ToastUtil.getInstant().show(ScanIdentityActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(ScanIdentityActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }


    private IdentityVerificationInfoBean identityVerificationInfoBean;

    //获取用户身份验证情况
    private void isCertified(){
        show();
        HttpParams params = new HttpParams();
        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.FINDIDENTITY_VERIFICATION_INFO, params, new RequestCallBack<IdentityVerificationInfoBean>() {

            @Override
            public void onSuccess(JsonResult<IdentityVerificationInfoBean> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    identityVerificationInfoBean = response.getObject();
                    if(identityVerificationInfoBean != null){
                        hsRefreshView(identityVerificationInfoBean);
                    }else{
                        identityVerificationInfoBean = new IdentityVerificationInfoBean();
                        hsRefreshView(identityVerificationInfoBean);
                    }
                } else {
                    ToastUtil.getInstant().show(ScanIdentityActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(ScanIdentityActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }


    //鸿胜科技新增刷新UI
    private void hsRefreshView(IdentityVerificationInfoBean idinfoBean) {
        int status = Integer.valueOf(idinfoBean.getStatus());
        switch (status) {                                   /** 此处有三种状态，-1：未成提交过任何资料; 1：已经提交部分资料； 0：认证通过 **/
            case 0:                                         //已经通过 只能预览
                ViewUtils.disableSubControls(tllRealName);
                tvTips.setVisibility(View.GONE);
                hsinitHasSubmitView();
                break;
            case 1:
                hsinitPartStatusView(idinfoBean);
                break;
            case -1:
                tllRealName.setTextWatcher(this, 0);
                tllIdentityNumber.setTextWatcher(this, 1);
                ivNegativeAdd.setVisibility(View.VISIBLE);
                ivPositiveAdd.setVisibility(View.VISIBLE);
                tllRealName.setEnabled(true);
                tllIdentityNumber.setEnabled(true);
                btnIdentifyPhotoCommit.setVisibility(View.VISIBLE);
                btnIdentifyPhotoCommit.setEnabled(true);
                tvTips.setVisibility(View.VISIBLE);
                break;
            default:
                hsinitHasSubmitView();
                break;
        }
        ViewUtils.disableSubControls(tllIdentityNumber);
    }

    //鸿胜科技新增加
    private void hsinitHasSubmitView() {
        ivNegativeAdd.setVisibility(View.GONE);
        ivPositiveAdd.setVisibility(View.GONE);
        IdentityInfoBean identityInfoBean = identityVerificationInfoBean.getIdentityInfo();
        String realName = "";
        String idCard = "";
        if(identityInfoBean != null){
            realName = identityInfoBean.getName();
            idCard = identityInfoBean.getIDCard();
        }

        if (!TextUtils.isEmpty(realName) && realName.length() > 1) {
            tllRealName.setRightContent("*" + realName.substring(1));
        }
        if (!TextUtils.isEmpty(idCard) && idCard.length() > 4) {
            tllIdentityNumber.setRightContent(idCard.substring(0, 2) + " *** *** *** " + idCard.substring(idCard.length() - 2));
        }
        btnIdentifyPhotoCommit.setVisibility(View.INVISIBLE);
        Glide.with(this).load(identityVerificationInfoBean.getFrontImg()).error(R.drawable.img_jzsb).into(ivPositiveImg);
        Glide.with(this).load(identityVerificationInfoBean.getReverseImg()).error(R.drawable.img_jzsb).into(ivNegativeImg);
        DMLog.d(identityVerificationInfoBean.getFrontImg());
        DMLog.d(identityVerificationInfoBean.getReverseImg());
    }

    /**
     *  当status 状态为1的时候提交了部分资料的情况下
     *  此处有三种状态，-1：未成提交过任何资料; 1：已经提交部分资料； 0：认证通过
     */
    private void hsinitPartStatusView(IdentityVerificationInfoBean identityVerificationInfoBean) {
        if (identityVerificationInfoBean != null) {
            String frontImg = identityVerificationInfoBean.getFrontImg();
            String reverseImg = identityVerificationInfoBean.getReverseImg();
            Glide.with(this).load(frontImg).error(R.drawable.img_jzsb).into(ivPositiveImg);
            Glide.with(this).load(reverseImg).error(R.drawable.img_jzsb).into(ivNegativeImg);
            if (frontImg == null || frontImg.equals("")) {
                ivPositiveAdd.setVisibility(View.VISIBLE);
                positivePath = "";
            } else {
                ivPositiveAdd.setVisibility(View.VISIBLE);
                positivePath = frontImg;
            }
            if (reverseImg == null || reverseImg.equals("")) {
                ivNegativeAdd.setVisibility(View.VISIBLE);
                OppositePath = "";
            } else {
                ivNegativeAdd.setVisibility(View.VISIBLE);
                OppositePath = reverseImg;
            }

            IdentityInfoBean identityInfoBean = identityVerificationInfoBean.getIdentityInfo();
            if(identityInfoBean != null){
                idCard = identityInfoBean.getIDCard();
                realName = identityInfoBean.getName();
                tllRealName.setRightContent(realName);
                tllIdentityNumber.setRightContent(idCard);
            }else {
                tllRealName.setRightContent("");
                tllIdentityNumber.setRightContent("");
            }

            tllRealName.setTextWatcher(this, 0);
            tllIdentityNumber.setTextWatcher(this, 1);
            tllRealName.setEnabled(true);
            tllIdentityNumber.setEnabled(true);

            btnIdentifyPhotoCommit.setVisibility(View.VISIBLE);
            btnIdentifyPhotoCommit.setEnabled(true);
            tvTips.setVisibility(View.VISIBLE);
        }
    }




    /**
     * 获取资料认证状态 2018.1.13
     */
    private void updateStatus() {
        show();
        HttpParams params = new HttpParams();
        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.FIND_USER_BASIC_INFO, params, new RequestCallBack<FindUserBasicInfoBean>() {
            @Override
            public void onSuccess(JsonResult<FindUserBasicInfoBean> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    basicInfoBean = response.getObject();
                    if(basicInfoBean != null){
                        int isNewsQianpen = basicInfoBean.getIsNewQianpen();                //判断是否是钱盆新用户0：是，1：否
                        if(isNewsQianpen == 0){                                             //如果是新注册用户直接走绑定银行卡等验证  0：是，1：否
                            if(isConfirml){ //如果是从认证中心跳转来的，则销毁
                                ScanIdentityActivity.this.finish();
                            }else {
                                Bundle bundle = new Bundle();
                                bundle.putSerializable(ConstantAppInfo.BASIC_INFO_BEAN, basicInfoBean);
                                startActivity(BindBankCardActivity.class, bundle,true); //跳转至绑定银行卡
                            }
                        }else{
                            ToastUtil.getInstant().show(getApplicationContext(),"系统检测到您当前帐号不符号我们平台贷款要求！");
                            startActivity(MainActivity.class, true);          //如果是在钱盆已经注册过的用户不让走绑定银行卡等下面的其他验证
                        }
                    }else{
                        ToastUtil.getInstant().show(getApplicationContext(),response.getDescription());
                    }
                } else {
                    ToastUtil.getInstant().show(ScanIdentityActivity.this, response.getDescription());
                }
            }


            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(ScanIdentityActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {
            }
        });
    }


    private void AgreementData(){

        JSONArray js = new JSONArray();
        js.put("10");

        AgreementApi.getAgreementName(this, js, new AgreementApi.AgreementNameCallBack() {
            @Override
            public void success(List<AgreementTitleBean> agreementName) {
                if (null != agreementName && !agreementName.isEmpty()) {

                    tvProtocol.setMovementMethod(LinkMovementMethod.getInstance());
                    tvProtocol.setHighlightColor(getResources().getColor(android.R.color.transparent));
                    SpanUtils spanUtils = new SpanUtils();
                    spanUtils.append(getString(R.string.Label_reading)).setForegroundColor(getResources().getColor(R.color.common_black_color_6)).append("《" + agreementName.get(0).getAgreementName() + "》").setClickSpan(new ClickableSpan() {
                        @Override
                        public void onClick(View view) {
                            Bundle bundle = new Bundle();
                            bundle.putSerializable(ConstantAppInfo.AGREEMENT_ID, "10");
                            startActivity(AgreementActivity.class, bundle);
                        }

                        @Override
                        public void updateDrawState(TextPaint ds) {
                            ds.setColor(getResources().getColor(R.color.common_blue_color_light));
                            ds.setUnderlineText(false);
                        }
                    });

                    tvProtocol.setText(spanUtils.create());
                }
            }
        });
    }



}